import axios from 'axios';
import type { MoodAnalysis, ImageGenerationRequest, GeneratedImage } from '../types';

// 魔搭社区API配置 - 使用相对路径通过Vite代理解决CORS问题
const MODELSCOPE_API_BASE = '/';
const API_KEY = (import.meta.env as any).VITE_MODELSCOPE_API_KEY || '';

// 创建axios实例
const apiClient = axios.create({
  baseURL: MODELSCOPE_API_BASE,
  headers: {
    'Authorization': `Bearer ${API_KEY}`,
    'Content-Type': 'application/json',
  },
});

/**
 * 分析文本情绪
 */
export async function analyzeMood(text: string): Promise<MoodAnalysis> {
  try {
    // 使用通义千问进行情绪分析
    const response = await apiClient.post('/chat/completions', {
      model: 'Qwen/Qwen2.5-7B-Instruct',
      messages: [
          {
            role: 'system',
            content: `你是一个专业的情绪提取分析师。请分析用户输入文本的情绪，并以JSON格式返回结果。
            返回格式：{
              "emotion": "主要情绪类型(joy/sadness/anger/fear/surprise/neutral之一)",
              "intensity": 情绪强度(0-1之间的数字),
              "confidence": 分析置信度(0-1之间的数字),
              "keywords": ["关键词1", "关键词2"],
              "description": "详细的情绪描述"
            }`
          },
          {
            role: 'user',
            content: `请分析以下文本的情绪：\n\n${text}`
          }
      ],
      max_tokens: 500,
      temperature: 0.3,
      response_format: { type: "json_object" }
    });

    const result = response.data.choices[0].message.content;
    
    // 尝试解析JSON响应
    try {
      const moodData = JSON.parse(result);
      return {
        emotion: moodData.emotion || 'neutral',
        intensity: Math.max(0, Math.min(1, moodData.intensity || 0.5)),
        confidence: Math.max(0, Math.min(1, moodData.confidence || 0.8)),
        keywords: Array.isArray(moodData.keywords) ? moodData.keywords : [],
        description: moodData.description || '情绪分析结果'
      };
    } catch (parseError) {
      // 如果JSON解析失败，返回默认结果
      console.warn('Failed to parse mood analysis result:', parseError);
      return {
        emotion: 'neutral',
        intensity: 0.5,
        confidence: 0.6,
        keywords: extractKeywords(text),
        description: '无法准确分析情绪'
      };
    }
  } catch (error) {
    console.error('Mood analysis failed:', error);
    throw new Error('情绪分析失败，请稍后重试');
  }
}

/**
 * 根据情绪生成图片
 */
export async function generateImage(request: ImageGenerationRequest): Promise<GeneratedImage> {
  try {
    // 根据情绪构建图片生成提示词
    const prompt = buildImagePrompt(request.text, request.mood, request.style);
    
    // 使用异步图片生成API
    const response = await apiClient.post('/images/generations', {
      model: 'black-forest-labs/FLUX.1-Krea-dev',
      prompt: prompt,
      negative_prompt: 'low quality, blurry, distorted, ugly, bad anatomy',
      style: request.style || '<auto>',
      size: '1024*1024',
      n: 1,
      seed: Math.floor(Math.random() * 1000000)
    }, {
      headers: {
        'X-ModelScope-Async-Mode': 'true'
      }
    });

    const taskId = response.data.task_id;
    
    // 等待任务完成
    let imageUrl = '';
    let attempts = 0;
    const maxAttempts = 20;
    
    while (attempts < maxAttempts) {
      await new Promise(resolve => setTimeout(resolve, 5000)); // 等待5秒
      
      const resultResponse = await apiClient.get(`/tasks/${taskId}`, {
        headers: {
          'X-ModelScope-Task-Type': 'image_generation'
        }
      });
      
      const taskData = resultResponse.data;
      
      if (taskData.task_status === 'SUCCEED') {
        imageUrl = taskData.output_images[0];
        break;
      } else if (taskData.task_status === 'FAILED') {
        throw new Error('图片生成失败');
      }
      
      attempts++;
    }
    
    if (!imageUrl) {
      throw new Error('图片生成超时');
    }
    
    return {
      url: imageUrl,
      prompt,
      style: request.style || 'auto',
      timestamp: Date.now()
    };
  } catch (error) {
    console.error('Image generation failed:', error);
    throw new Error('图片生成失败，请稍后重试');
  }
}

/**
 * 构建图片生成提示词
 */
function buildImagePrompt(text: string, mood: MoodAnalysis, style?: string): string {
  const emotionStyles = {
    joy: '明亮温暖的色彩，阳光，花朵，笑容，积极向上的氛围',
    sadness: '柔和的蓝色调，雨滴，云朵，宁静忧郁的氛围',
    anger: '强烈的红色和橙色，火焰，闪电，动态的线条',
    fear: '深色调，阴影，迷雾，神秘紧张的氛围',
    surprise: '鲜艳的色彩，星光，爆炸效果，动感的构图',
    neutral: '平衡的色彩，简洁的构图，和谐宁静的氛围'
  };

  const emotionStyle = emotionStyles[mood.emotion as keyof typeof emotionStyles] || emotionStyles.neutral;
  const intensityDesc = mood.intensity > 0.7 ? '强烈的' : mood.intensity > 0.4 ? '温和的' : '淡淡的';
  
  let prompt = `${intensityDesc}${mood.description}，${emotionStyle}`;
  
  // 添加关键词
  if (mood.keywords.length > 0) {
    prompt += `，体现${mood.keywords.join('、')}的感觉`;
  }
  
  // 添加艺术风格
  const artStyle = style || '水彩画风格';
  prompt += `，${artStyle}，高质量，艺术感，唯美`;
  
  return prompt;
}

/**
 * 简单的关键词提取（备用方案）
 */
function extractKeywords(text: string): string[] {
  // 这是一个简化的关键词提取，实际应用中可以使用更复杂的NLP技术
  const words = text.split(/\s+|[，。！？、；：]/);
  return words.filter(word => word.length > 1).slice(0, 5);
}